package com.nl.controller.web.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.nl.controller.xuyi.bean.XuYiCheckInfoBo;
import com.nl.controller.xuyi.bean.XuYiContentTemplateInfo;
import com.nl.controller.xuyi.bean.contentcheck.ContentCheckInfo;
import com.nl.controller.xuyi.mapper.XuYiCheckMapper;
import com.nl.controller.xuyi.mapper.XuYiContentTemplateMapper;
import com.nl.controller.xuyi.service.XuYiContentCheckService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.nl.controller.web.bean.CmppReplyInfo;
import com.nl.controller.web.bean.SmsMgrTemplateInfo;
import com.nl.controller.web.bean.SmsUsers;
import com.nl.controller.web.mapper.SmsMgrTemplateInfoMapper;
import com.nl.controller.web.mapper.SmsTemplateCheckMapper;
import com.nl.controller.web.mapper.SmsUserMapper;
import com.nl.controller.web.mapper.TimedTaskMapper;
import com.nl.controller.xuyi.bean.XuYiBlackUserInfo;
import com.nl.controller.xuyi.mapper.XuYiBlackMapper;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class TimedTaskService {
	@Autowired
	private TimedTaskMapper timedTaskMapper;
	@Autowired
	private SmsTemplateCheckMapper smsTemplateCheckMapper;
	@Autowired
	private SmsMgrTemplateInfoService smsMgrTemplateInfoService;
	@Autowired
	private SmsMgrTemplateInfoMapper smsMgrTemplateInfoMapper;
	@Autowired
	private LoginService loginService;
	@Autowired
	private SmsUserService smsUserService;
	@Autowired
	private SmsUserMapper smsUserMapper;
	@Autowired
	private XuYiBlackMapper xuYiBlackMapper;
	@Autowired
	private XuYiContentTemplateMapper xuYiContentTemplateMapper;
	@Autowired
	private XuYiCheckMapper xuYiCheckMapper;
	@Autowired
	private XuYiContentCheckService xuYiContentCheckService;





	public void checkMgr(Map< String , String > map){
		List<CmppReplyInfo> list = new ArrayList<CmppReplyInfo>();
		list=timedTaskMapper.checkCmpp();
		if (null !=list && !list.isEmpty()) {
			for (CmppReplyInfo cmppReplyInfo : list) {
				String srcTerminalId = cmppReplyInfo.getSrcTerminalId();
				String msgContent = cmppReplyInfo.getMsgContent().trim();
				log.info("短信审核上行参数: 号码"+srcTerminalId+";消息内容"+msgContent);
				if (msgContent.indexOf("-")!=-1) {
					String[] split = msgContent.split("-");
					if (split.length == 3) {
						String flag = split[0].toUpperCase();
						String mgrIdNum = split[1].trim();
						String mgrFlag = split[2].trim();
						if (srcTerminalId.startsWith("86")) {
							srcTerminalId = srcTerminalId.substring(2);
						}

						if ("YJ".equals(mgrFlag)||"XYGD".equals(mgrFlag))
						{


							String mgrId = mgrIdNum.split("\\+")[0];
							log.info("号码"+srcTerminalId+";消息内容"+flag+";项目编码:"+mgrId);
							SmsMgrTemplateInfo smsMgrTemplateInfo = smsMgrTemplateInfoMapper.findMgrTemplateByMgrId(mgrId);
							if (null == smsMgrTemplateInfo) {
								continue;
							}
							List<SmsUsers> cityUsers =smsUserService.findCityUsersbyCityId( smsMgrTemplateInfo.getCityId());
							List<SmsUsers> checkUsers =smsUserService.findCheckUsersbyCityId( smsMgrTemplateInfo.getCityId());
							List<String> cityMsisdns = new ArrayList<String>();
							List<String> checkMsisdns = new ArrayList<String>();
							for (SmsUsers cityUser : cityUsers) {
								log.info(cityUser.getMsisdn());
								cityMsisdns.add(cityUser.getMsisdn());
							}
							for (SmsUsers checkUser : checkUsers) {
								log.info(checkUser.getMsisdn());
								checkMsisdns.add(checkUser.getMsisdn());
							}

							ContentCheckInfo contentCheckInfo1=new ContentCheckInfo() ;
							if("XYGD".equals(mgrFlag)){
								//根据项目id找到最新的审核记录，变更为已审核
								ContentCheckInfo contentCheckInfo = new ContentCheckInfo();
								contentCheckInfo.setMgrId(mgrId);
								List<ContentCheckInfo> xuYiCheckInfoBoList = xuYiCheckMapper.findCheckList(contentCheckInfo);


								if(!CollectionUtils.isEmpty(xuYiCheckInfoBoList)){
									contentCheckInfo1 = xuYiCheckInfoBoList.get(0);
									contentCheckInfo1.setCheckOperatorTel(srcTerminalId);
									contentCheckInfo1.setRemark("短信上行审核");
									contentCheckInfo1.setCheckMethod("2");
									if (null == contentCheckInfo1) {
										continue;
									}
								}else{
									continue;
								}
							}
							//应急短信地市领导审核
							if (!checkMsisdns.isEmpty() && checkMsisdns.contains(srcTerminalId)) {
								if (map.containsKey(mgrIdNum+"LDXM")) {
									log.info(mgrIdNum+"已审核；审核人"+map.get(mgrIdNum+"LDXM"));
									continue;
								}
								log.info("地市领导审核开始");
								Map<String, Object> map1 = new HashMap<String, Object>();
								map1.put("mgrId", mgrId);
								StringBuffer sBuffer = new StringBuffer();
								sBuffer.append("【江苏省应急平台】您好，项目：");
								sBuffer.append(smsMgrTemplateInfo.getName());
								sBuffer.append("，已由"+srcTerminalId+"复审完毕；");
								Map<String, Object> map2 = new HashMap<String, Object>();
								map2.put("duty", "0");
								List<SmsUsers> provinceUsers = smsUserMapper.findUser(map2);

								if ("Y".equals(flag)) {

									map1.put("state", "2");
									sBuffer.append("审核结果：通过。");

									//审核通过，通知系统管理员
									for (SmsUsers smsUsers : provinceUsers) {
										loginService.sendCode(smsUsers.getMsisdn(),sBuffer.toString());
									}

									//更新审核表状态为已审核
									if("XYGD".equals(mgrFlag)){
										contentCheckInfo1.setCheckState("1");
										xuYiContentCheckService.updateCheckInfo(contentCheckInfo1);
									}


								}else if ("N".equals(flag)) {


									map1.put("state", "3");
									sBuffer.append("审核结果：不通过。");
									//更新审核表状态为已审核
									if("XYGD".equals(mgrFlag)){
										contentCheckInfo1.setCheckState("2");
										xuYiContentCheckService.updateCheckInfo(contentCheckInfo1);
									}

								}else {
									continue ;
								}
								//更新审核次数
								Integer checkNum = Integer.parseInt(smsMgrTemplateInfo.getCheckNum())+1;
								Integer result2 = smsMgrTemplateInfoService.updateCheckNum(checkNum+"",mgrId);


								int result=-1;

								try {
									//复审结果，通知项目创建人
									if (null != smsMgrTemplateInfo.getMsisdn() && !"".equals(smsMgrTemplateInfo.getMsisdn())) {
										int result1 = loginService.sendCode(smsMgrTemplateInfo.getMsisdn(),sBuffer.toString());
										String logString = result1==1 ? "短信发送成功" : "短信发送失败";
										log.info(logString+";短信内容为:"+sBuffer.toString());
									}

									//通知地市管理员
									for(String cityMsisdn:cityMsisdns){
										int insertResult=loginService.sendCode(cityMsisdn,sBuffer.toString());
										String logString = insertResult==1 ? "短信发送成功" : "短信发送失败";
										log.info(logString+";短信内容为:"+sBuffer.toString());
									}

									sBuffer.append("无需重复审核。");
									//通知其他地市领导
									for(String checkMsisdn:checkMsisdns){
										if(!checkMsisdn.equals(srcTerminalId)){
											try {
												int result1 = loginService.sendCode(checkMsisdn,sBuffer.toString());
												String logString = result1==1 ? "短信发送成功" : "短信发送失败";
												log.info(logString+";短信内容为:"+sBuffer.toString());
											}
											catch (Exception e) {
												log.error("短信模板审核异常"+e.toString());
												e.printStackTrace();
											}
										}else{
											log.info("该账号为此次审核人，无需通知。");
										}
									}

									result = smsTemplateCheckMapper.modifyTemplateStatus(map1);


								} catch (Exception e) {
									log.error("模板审核异常"+e.toString());
									e.printStackTrace();
								}
								String logString1 = result==1 ? "短信内容审核成功,入表成功" : "短信内容审核失败,入表失败";
								log.info(logString1+";result:"+result);
								//判断该项目批次已审核
								map.put(mgrIdNum+"LDXM", srcTerminalId);
								//变更审核次数
								int updateResult = xuYiCheckMapper.updateCheckNumber(contentCheckInfo1.getCheckId(),checkNum+"",srcTerminalId,"短信上行审核");
							}
							//地市管理员审核
							else if (!cityMsisdns.isEmpty() && cityMsisdns.contains(srcTerminalId)) {

									if (map.containsKey(mgrIdNum+"DSXM")) {
									log.info(mgrIdNum+"已审核;审核人"+map.get(mgrIdNum+"DSXM"));
									continue;
								}

								String cityMsisdnContent = "【江苏省应急平台】您好，"+smsMgrTemplateInfo.getCityName()+"市项目：" + smsMgrTemplateInfo.getName()+"，已由"+srcTerminalId+"初审完毕，无需重复审核。";

								//审核通过
								if ("Y".equals(flag)) {
									Integer checkNum = Integer.parseInt(smsMgrTemplateInfo.getCheckNum())+1;
									try {
										Integer result = smsMgrTemplateInfoService.updateCheckNum(checkNum+"",mgrId);
										//审核短信做加一操作
										checkNum = checkNum+1;
										if (result ==1 ) {
											log.info("更新审核次数成功");
										}
									} catch (Exception e) {
										log.error("更新审核次数失败"+e.toString());
										e.printStackTrace();
									}
									StringBuffer sbf = new StringBuffer();
									String contents = "【江苏省应急平台】您好，"+smsMgrTemplateInfo.getCityName()+"市项目：" + smsMgrTemplateInfo.getName()+"，已由"+srcTerminalId+"初审完毕，请进行复审，";
									sbf.append(contents);
									sbf.append("短信内容如下 :"+smsMgrTemplateInfo.getContent());
									if("YJ".equals(mgrFlag)){
										sbf.append("，审核通过请回复\'Y-"+mgrId+"+"+checkNum+"-YJ\'");
										sbf.append("，审核不通过请回复\'N-"+mgrId+"+"+checkNum+"-YJ\'。");
									}else if("XYGD".equals(mgrFlag)){
										sbf.append("，审核通过请回复\'Y-"+mgrId+"+"+checkNum+"-XYGD\'。");
										sbf.append("，审核不通过请回复\'N-"+mgrId+"+"+checkNum+"-XYGD\'。");
									}

									//地市管理员审核完成，通知地市领导复审
									for (String string : checkMsisdns) {
										try {
											int result1 = loginService.sendCode(string,sbf.toString());
											String logString = result1==1 ? "短信发送成功" : "短信发送失败";
											log.info(logString+";短信内容为:"+sbf.toString());
										}
										catch (Exception e) {
											log.error("短信模板审核异常"+e.toString());
											e.printStackTrace();
										}
									}
								}else if ("N".equals(flag)) {

									//更新审核表状态为已审核
									if("XYGD".equals(mgrFlag)){
										contentCheckInfo1.setCheckState("2");
										xuYiContentCheckService.updateCheckInfo(contentCheckInfo1);
									}

									Integer checkNum = Integer.parseInt(smsMgrTemplateInfo.getCheckNum())+1;
									Integer result2 = smsMgrTemplateInfoService.updateCheckNum(checkNum+"",mgrId);

									StringBuffer sBuffer = new StringBuffer();
									sBuffer.append("您好，项目：");
									sBuffer.append(smsMgrTemplateInfo.getName());
									sBuffer.append("，已由"+srcTerminalId+"初审完毕。");
									sBuffer.append("审核结果：不通过。");
									int result=-1;
									try {
										result = loginService.sendCode(smsMgrTemplateInfo.getMsisdn(),sBuffer.toString());
										String logString = result==1 ? "短信发送成功" : "短信发送失败";
										log.info(logString+";短信内容为:"+sBuffer.toString());
									}catch (Exception e) {
										log.error("短信发送失败;短信内容:"+sBuffer.toString());
										e.printStackTrace();
									}
								}else {
									continue ;
								}
								map.put(mgrIdNum+"DSXM", srcTerminalId);
								//变更审核次数
								String checkNum = Integer.parseInt(smsMgrTemplateInfo.getCheckNum())+1+"";
								int updateResult = xuYiCheckMapper.updateCheckNumber(contentCheckInfo1.getCheckId(),checkNum,srcTerminalId,"短信上行审核");

								//通知地市其他地市管理员无需重复审核。
								for(String cityMsisdn:cityMsisdns){
									//剔除地市审核人
									if(!cityMsisdn.equals(srcTerminalId)){
										try {
											int result1 = loginService.sendCode(cityMsisdn,cityMsisdnContent);
											String logString = result1==1 ? "短信发送成功" : "短信发送失败";
											log.info(logString+";短信内容为:"+cityMsisdnContent.toString());
										}
										catch (Exception e) {
											log.error("短信模板审核异常"+e.toString());
											e.printStackTrace();
										}
									}else{
										log.info("该账号为此次审核人，无需通知。");
									}
								}
							}

						}
						else if("XYMB".equals(mgrFlag)){
							//盱眙供电局短信模板审核
							String tempId = mgrIdNum.split("\\+")[0];
							log.info("号码"+srcTerminalId+";消息内容"+flag+";盱眙供电局短信模板编码:"+tempId);
							//XuYiContentTemplateInfo xuYiContentTemplateInfo = xuYiContentTemplateMapper.findContentTemplateByContentId(tempId);
							ContentCheckInfo contentCheckInfo = new ContentCheckInfo();
							contentCheckInfo.setContentTempId(tempId);
							List<ContentCheckInfo> xuYiCheckInfoBoList = xuYiCheckMapper.findCheckList(contentCheckInfo);
							ContentCheckInfo contentCheckInfo1 ;

							if(!CollectionUtils.isEmpty(xuYiCheckInfoBoList)){
								contentCheckInfo1 = xuYiCheckInfoBoList.get(0);
								if (null == contentCheckInfo1) {
									continue;
								}
							}else{
								continue;
							}

							//淮安地市12
							List<SmsUsers> cityUsers =smsUserService.findCityUsersbyCityId("12");
							List<SmsUsers> checkUsers =smsUserService.findCheckUsersbyCityId("12");
							List<String> cityMsisdns = new ArrayList<String>();
							List<String> checkMsisdns = new ArrayList<String>();
							for (SmsUsers cityUser : cityUsers) {
								log.info(cityUser.getMsisdn());
								cityMsisdns.add(cityUser.getMsisdn());
							}
							for (SmsUsers checkUser : checkUsers) {
								log.info(checkUser.getMsisdn());
								checkMsisdns.add(checkUser.getMsisdn());
							}

							contentCheckInfo1.setCheckOperatorTel(srcTerminalId);
							//审核方式为短信上行审核
							contentCheckInfo1.setCheckMethod("2");

							//应急短信地市领导审核
							if (!checkMsisdns.isEmpty() && checkMsisdns.contains(srcTerminalId)) {
								if (map.containsKey(mgrIdNum+"LDXYMB")) {
									log.info(mgrIdNum+"已审核；审核人"+map.get(mgrIdNum+"LDXYMB"));
									continue;
								}
								int result=-1;
								log.info("地市领导审核开始");

								Map<String, Object> map1 = new HashMap<String, Object>();
								StringBuffer sBuffer = new StringBuffer();
								sBuffer.append("【江苏省应急平台】您好，盱眙供电局短信模板：");
								sBuffer.append(contentCheckInfo1.getContentTempName());
								sBuffer.append("，已由"+srcTerminalId+"审核；");
								Map<String, Object> map2 = new HashMap<String, Object>();
								map2.put("duty", "0");
								List<SmsUsers> provinceUsers = smsUserMapper.findUser(map2);
								if ("Y".equals(flag)) {
									//变更审核内容表中的审核状态
									contentCheckInfo1.setCheckState("1");
									contentCheckInfo1.setRemark("短信上行审核");


									xuYiContentCheckService.updateCheckInfo(contentCheckInfo1);

									//处理审核结果，入库
									xuYiContentCheckService.dealCheckResult(contentCheckInfo1.getCheckId());


									sBuffer.append("审核结果：通过。");
									//审核通过，通知系统管理员
									for (SmsUsers smsUsers : provinceUsers) {
										loginService.sendCode(smsUsers.getMsisdn(),sBuffer.toString());
									}
								}else if ("N".equals(flag)) {

									contentCheckInfo1.setCheckState("2");
									contentCheckInfo1.setRemark("短信上行审核");
									xuYiContentCheckService.updateCheckInfo(contentCheckInfo1);

									//xuYiContentCheckService.dealCheckResult(contentCheckInfo1.getCheckId());

									sBuffer.append("审核结果：不通过。");
								}else {
									continue ;
								}

								try {
									//复审结果，通知模板编辑人
									if (null != contentCheckInfo1.getOperatorTel() && !"".equals(contentCheckInfo1.getOperatorTel())) {
										result = loginService.sendCode(contentCheckInfo1.getOperatorTel(),sBuffer.toString());
										String logString = result==1 ? "短信发送成功" : "短信发送失败";
										log.info(logString+";短信内容为:"+sBuffer.toString());
									}
									sBuffer.append("无需重复审核。");
									for(String checkMsisdn:checkMsisdns){
										if(!checkMsisdn.equals(srcTerminalId)){
											try {
												int result2 = loginService.sendCode(checkMsisdn,sBuffer.toString());
												String logString = result2==1 ? "短信发送成功" : "短信发送失败";
												log.info(logString+";短信内容为:"+sBuffer.toString());
											}
											catch (Exception e) {
												log.error("短信模板审核异常"+e.toString());
												e.printStackTrace();
											}
										}else{
											log.info("该账号为此次审核人，无需通知。");
										}
									}
									//result = xuYiContentTemplateMapper.modifyContentTemplate(xuYiContentTemplateInfo);
								} catch (Exception e) {
									log.error("模板审核异常"+e.toString());
									e.printStackTrace();
								}
								String logString1 = result==1 ? "短信内容审核成功,入表成功" : "短信内容审核失败,入表失败";
								log.info(logString1+";result:"+result);
								//判断该项目批次已审核
								map.put(mgrIdNum+"LDXYMB", srcTerminalId);
							}
							//地市管理员审核
							else if (!cityMsisdns.isEmpty() && cityMsisdns.contains(srcTerminalId)) {
								String cityMsisdnContent = "【江苏省应急平台】您好，盱眙供电局短信模板：" +contentCheckInfo1.getContentTempName()+"，已由"+srcTerminalId+"完成审核，无需重复审核。";

								//判断是否已审核
								if (map.containsKey(mgrIdNum+"DSXYMB")) {
									log.info(tempId+"已审核;审核人"+map.get(mgrIdNum+"DSXYMB"));
									continue;
								}
								//实际审核次数
								String checkNum;
								//审核短信中的审核次数
								String checkNum2;
								//审核通过
								if ("Y".equals(flag)) {
									//判断该项目批次已审核
									map.put(mgrIdNum+"DSXYMB", srcTerminalId);
									checkNum = Integer.valueOf(contentCheckInfo1.getCheckNumber())+1+"";
									//变更审核次数
									int updateResult = xuYiCheckMapper.updateCheckNumber(contentCheckInfo1.getCheckId(),checkNum,srcTerminalId,"短信上行审核");

									checkNum2 = Integer.valueOf(checkNum)+1+"";

									StringBuffer sbf = new StringBuffer();
									String contents = "【江苏省应急平台】您好，盱眙供电局短信模板：" +contentCheckInfo1.getContentTempName()+"，已由"+srcTerminalId+"完成初审，请复审，";

									sbf.append(contents);
									sbf.append("模板内容如下 :"+contentCheckInfo1.getContentTemp());
									sbf.append("，审核通过请回复\'Y-"+contentCheckInfo1.getContentTempId()+"+"+checkNum2+"-XYMB\'");
									sbf.append("，审核不通过请回复\'N-"+contentCheckInfo1.getContentTempId()+"+"+checkNum2+"-XYMB\'。");

									//地市管理员审核完成，通知地市领导复审
									for (String string : checkMsisdns) {
										try {
											int result1 = loginService.sendCode(string,sbf.toString());
											String logString = result1==1 ? "短信发送成功" : "短信发送失败";
											log.info(logString+";短信内容为:"+sbf.toString());
										}
										catch (Exception e) {
											log.error("短信模板审核异常"+e.toString());
											e.printStackTrace();
										}
									}
								}else if ("N".equals(flag)) {
									map.put(mgrIdNum+"DSXYMB", srcTerminalId);

									contentCheckInfo1.setCheckState("2");
									contentCheckInfo1.setRemark("短信上行审核");
									xuYiContentCheckService.updateCheckInfo(contentCheckInfo1);

									//xuYiContentCheckService.dealCheckResult(contentCheckInfo1.getCheckId());

									StringBuffer sBuffer = new StringBuffer();
									sBuffer.append("您好，盱眙供电局短信模板：");
									sBuffer.append(contentCheckInfo1.getContentTempName());
									sBuffer.append("，已由"+srcTerminalId+"审核。");
									sBuffer.append("审核结果：不通过。");
									int result=-1;
									try {
										result = loginService.sendCode(contentCheckInfo1.getOperatorTel(),sBuffer.toString());
										String logString = result==1 ? "短信发送成功" : "短信发送失败";
										log.info(logString+";短信内容为:"+sBuffer.toString());
									}catch (Exception e) {
										log.error("短信发送失败;短信内容:"+sBuffer.toString());
										e.printStackTrace();
									}
								}else {
									continue ;
								}
								//通知地市其他地市管理员无需重复审核。
								for(String cityMsisdn:cityMsisdns){
									//剔除地市审核人
									if(!cityMsisdn.equals(srcTerminalId)){
										try {
											int result1 = loginService.sendCode(cityMsisdn,cityMsisdnContent);
											String logString = result1==1 ? "短信发送成功" : "短信发送失败";
											log.info(logString+";短信内容为:"+cityMsisdnContent.toString());
										}
										catch (Exception e) {
											log.error("短信模板审核异常"+e.toString());
											e.printStackTrace();
										}
									}else{
										log.info("该账号为此次审核人，无需通知。");
									}
								}
							}
						}
						else if ("HY".equals(mgrFlag)) {

						}else if ("JZZW".equals(mgrFlag)) {

						}
					}
				}else{
					//盱眙供电局项目退订
					if("TD".equals(msgContent.toUpperCase())){
						try {
							if (srcTerminalId.startsWith("86")) {
								srcTerminalId = srcTerminalId.substring(2);
							}
							List<XuYiBlackUserInfo> blackUserInfoList = xuYiBlackMapper.findBlackUserByTel(srcTerminalId);
							XuYiBlackUserInfo blackUserInfo;
							int insertResult = 0;
							if(!CollectionUtils.isEmpty(blackUserInfoList)){
								//黑名单表里已经有该号码
								log.info(srcTerminalId+"-该号码已存在！");
								continue;
							}else{
								blackUserInfo = new XuYiBlackUserInfo();
								blackUserInfo.setPhoneNumber(srcTerminalId);
								blackUserInfo.setIsValid("1");
								insertResult= xuYiBlackMapper.insertBlackUser(blackUserInfo);
								if(insertResult ==1){
									log.info("新增黑名单号码:"+srcTerminalId+"-成功");
								}else{
									log.info("新增黑名单号码:"+srcTerminalId+"-失败");
								}
							}
						} catch (Exception e) {
							log.info("处理盱眙供电局项目退订短信出现异常"+e.toString());
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
}
